'use client';
import React, { useState, useEffect, useRef, FC } from 'react';

type MyLazyComponentProps = {
	children: React.ReactNode;
};
// #----------- 上: ts类型定义 ----------- 分割线 ----------- 下: JS代码 -----------

const MyLazyComponent: FC<MyLazyComponentProps> = ({ children }) => {
	const [loaded, setLoaded] = useState(false);
	const ref = useRef(null);

	useEffect(() => {
		const observer = new IntersectionObserver((entries) => {
			console.log(entries[0].isIntersecting);

			if (entries[0].isIntersecting) {
				setLoaded(true);
				observer.disconnect();
			}
		});

		if (ref.current) {
			observer.observe(ref.current);
		}

		return () => {
			observer.disconnect();
		};
	}, [ref]);

	return (
		<div ref={ref}>
			{
				/* 组件内容 */
				loaded ? children : null
			}
		</div>
	);
};

export default MyLazyComponent;
